<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;
use App\Models\Category;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     * 实现基于Vite manifest的资产版本管理，当资产更新时自动刷新页面
     *
     * @see https://inertiajs.com/asset-versioning
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function version(Request $request): ?string
    {
        // 使用Vite manifest文件的hash作为版本号
        // 当manifest.json内容改变时（即资产重新构建），版本号会改变
        // Inertia会自动检测版本变化并触发全页刷新，确保用户获得最新资产
        $manifestPath = public_path('build/manifest.json');
        
        if (file_exists($manifestPath)) {
            // 使用文件的hash作为版本标识
            // 当manifest内容变化时，hash会改变，触发页面刷新
            return md5_file($manifestPath);
        }

        // 如果manifest不存在（开发环境可能未构建），使用默认处理
        return parent::version($request);
    }

    /**
     * Defines the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function share(Request $request): array
    {
        // 注意：parent::share() 已经自动包含了验证错误（errors）
        // 验证错误会自动通过 $page.props.errors 共享到前端，无需额外配置
        return array_merge(parent::share($request), [
            'auth' => [
                'user' => $request->user() ? [
                    'id' => $request->user()->id,
                    'name' => $request->user()->name,
                    'email' => $request->user()->email,
                    'profile_photo_url' => $request->user()->profile_photo_url,
                ] : null,
            ],
            'app' => [
                'name' => config('app.name'),
                'debug' => config('app.debug'),
            ],
            'flash' => [
                'message' => fn () => $request->session()->get('message'),
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
                'warning' => fn () => $request->session()->get('warning'),
                'info' => fn () => $request->session()->get('info'),
            ],
            'categories' => fn () => Category::select('name', 'slug')->get(),
        ]);
    }
}
